package com.jsl.action;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.*;
import org.apache.http.client.HttpClient;

import java.io.BufferedReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import java.io.InputStreamReader;

import java.util.*;




public class SsoAction {

    private static final String appSecret = "6ad1ed0c19084c708a953dbcbe9d9144";

    private static  final String appId = "70eb9ca371974e5ab865cb05c458a531";

   // private static  final String go = "https://oa.hbjinshenglan.com/wui/sso/index.jsp";
   private static  final String go = "https://oa.hbjinshenglan.com/wui/sso/guide.html";

    public static void main(String[] args) throws UnsupportedEncodingException {
        //System.out.println(ssoPage());
//        execute(getUserInfo("98de4031-7012-4b9b-bdae-0a41a2078f2d"));
        // 负差
      //  String go1 = encodeUrl("https://oa.hbjinshenglan.com/mobilemode/mobile/view.html?appid=16&moduleid=1373748054#&page_209");
     //   String url1 = "https://oa.hbjinshenglan.com/wui/sso/guide.html?targetUrl="+go1;
//
       // String go2 = encodeUrl("https://oa.hbjinshenglan.com/spa/workflow/static4mobile/index.html#/center/doing?moduleid=10");
       // String url2 = "https://oa.hbjinshenglan.com/wui/sso/guide.html?targetUrl="+go2;

      //  String go3 = encodeUrl("https://oa.hbjinshenglan.com/spa/workflow/static4mobile/index.html#/center/doing?moduleid=1");
     //   String url3 = "https://oa.hbjinshenglan.com/wui/sso/guide.html?targetUrl="+go3;
         String url = "https://oa.hbjinshenglan.com/wui/sso/guide.html?targetUrl=https%3A%2F%2Foa.hbjinshenglan.com%2Fspa%2Fworkflow%2Fstatic4form%2Findex.html%3F%23%2Fmain%2Fworkflow%2Freq%3Frequestid%3D378538&taskId=1100583";
        System.out.println(encodeUrl(url));
//        System.out.println(url2);
//       System.out.println(url3);
//       String a = "https://oa.hbjinshenglan.com/mobilemode/mobile/view.html?appid=16&moduleid=1373748054#&page_209";
//       String b = "https://oa.hbjinshenglan.com/spa/workflow/static4mobile/index.html#/center/doing?moduleid=10";
//        System.out.println(addSsoToken(a, "123456"));
//        System.out.println(addSsoToken(b, "123456"));
//       String encodedUrl =  encodeUrl("https://oa.hbjinshenglan.com/mobilemode/mobile/view.html?appHomepageId=196");
//        System.out.println(encodedUrl);
//        String str = "https％3A％2F％2Foa.hbjinshenglan.com％2Fmobilemode％2Fmobile％2Fview.html％3FappHomepageId％3D196";
//        System.out.println(decodeUrl(str));
//        System.out.println(decodeUrl(encodedUrl));
        //System.out.println(decodeUrl("https://www.fjjslds.com/%20https://oa.hbjinshenglan.com/wui/sso/guide.html?targetUrl=https%253A%252F%252Foa.hbjinshenglan.com%252Fspa%252Fworkflow%252Fstatic4form%252Findex.html%253F%2523%252Fmain%252Fworkflow%252Freq%253Frequestid%253D355355&taskId=TASK61567"));
       // System.out.println(decodeUrl("https://oa.hbjinshenglan.com/wui/sso/guide.html?targetUrl=https%3A%2F%2Foa.hbjinshenglan.com%2Fspa%2Fworkflow%2Fstatic4form%2Findex.html%3F%23%2Fmain%2Fworkflow%2Freq%3Frequestid%3D378634&taskId=1101472"));
        System.out.println(decodeUrl("https://oa.hbjinshenglan.com/wui/sso/guide.html?targetUrl=https%3A%2F%2Foa.hbjinshenglan.com%2Fspa%2Fworkflow%2Fstatic4form%2Findex.html%3F%23%2Fmain%2Fworkflow%2Freq%3Frequestid%3D378538&taskId=1100583"));
    }

    public static String addSsoToken(String url, String token) {
        // 使用正则表达式：匹配第一个不在 # 后面的 '?'
        // 匹配规则：前面不是 '#'，且 '?' 不在 '#' 之后
        int indexOfQuestionMark = -1;

        // 遍历字符，手动查找第一个不在 '#' 后面的 '?'
        boolean hashFound = false;
        for (int i = 0; i < url.length(); i++) {
            char c = url.charAt(i);
            if (c == '#') {
                hashFound = true;
            } else if (c == '?' && !hashFound) {
                indexOfQuestionMark = i;
                break;
            }
        }

        if (indexOfQuestionMark == -1) {
            // 没有找到合法的 '?', 在 .html 或路径末尾后插入 ?ssoToken=...
            int hashIndex = url.indexOf("#");
            if (hashIndex != -1) {
                return url.substring(0, hashIndex) + "?ssoToken=" + token + url.substring(hashIndex);
            } else {
                return url + "?ssoToken=" + token;
            }
        } else {
            // 在第一个合法的 '?' 后插入 ssoToken=... 到查询字符串最前面
            return url.substring(0, indexOfQuestionMark + 1) +
                    "ssoToken=" + token + "&" +
                    url.substring(indexOfQuestionMark + 1 ); // 跳过 '?'
        }
    }

    public static String encodeUrl(String str) {
        try {
            return URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return "https://oa.hbjinshenglan.com/spa/em/mobile.html";
        }
    }

    public static String decodeUrl(String str){
        try {
            return java.net.URLDecoder.decode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return "https://oa.hbjinshenglan.com/spa/em/mobile.html";
        }
    }



    // 单点到平台登录页
    public static String ssoPage() {
        HashMap<String, String> map = new HashMap<>();
        map.put("appSecret", appSecret);
        String timestamp = Instant.now().toEpochMilli() + "";
        map.put("appId", appId);
        map.put("iplatformCode", "authorize");
        map.put("timestamp", timestamp);
        map.put("go", go);
        String sortString = mapSortToUrlParam(map, true);

        // 构造请求参数
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("appId", appId);
        paramMap.put("iplatformCode", "authorize");
        paramMap.put("timestamp", timestamp);
        paramMap.put("go", go);
        String sign = DigestUtils.md5Hex(sortString);
        paramMap.put("sign", sign);

        // 路径
        String url = "https://www.fjjslds.com/iplatform";
        return  url+"?"+mapSortToUrlParam(paramMap, true);
    }


    // 验证用户信息
    public static JSONObject getUserInfo(String token){
        HashMap<String, String> map = new HashMap<>();
        map.put("appSecret", appSecret);
        String timestamp = Instant.now().toEpochMilli() + "";
        String formattedTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()).format(Instant.now());
        System.out.println(formattedTime);
        map.put("appId", appId);
        map.put("iplatformCode", "validUser");
        map.put("timestamp", timestamp);
        map.put("token", token);
        String sortString = mapSortToUrlParam(map, true);

        // 构造请求参数
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("appId", appId);
        paramMap.put("iplatformCode", "validUser");
        paramMap.put("timestamp", timestamp);
        paramMap.put("token", token);
        String sign = DigestUtils.md5Hex(sortString);
        paramMap.put("sign", sign);

        // 路径
        String url = "https://www.fjjslds.com/authValid";

        String result = doPost(url, paramMap);
        System.out.println("appId:"+appId);
        System.out.println("token:"+token);
        System.out.println("iplatformCode:validUser");
        System.out.println("timestamp:"+timestamp);
        System.out.println("sign:"+sign);
        System.out.println(result);

        // 解析json
        return JSONObject.parseObject(result);
    }

    public static void execute(JSONObject jsonObject){
        // 成功获取到code
        if(jsonObject.getIntValue("code") == 0){
            // 获取嵌套对象 data
            JSONObject data = jsonObject.getJSONObject("data");
            if(data == null) System.out.println("data为空");
            // 手机号
            String mobilephone = data.getString("mobilephone");
            // 身份证号
            String idcard = data.getString("idcard");
        }else {
            String message = jsonObject.getString("message");
            System.out.println(message);
        }
    }


    /**
     * 签名生成函数
     *
     * @param map
     * @param allrowEmpty
     * @return
     */
    public static String mapSortToUrlParam(Map<String, String> map, Boolean allrowEmpty) {
        List<String> keys = new ArrayList<>(map.keySet());
        Collections.sort(keys, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                // 返回相反的compare
                return o1.compareTo(o2);
            }
        });
        Iterator<String> iter = keys.iterator();
        StringBuffer signStr = new StringBuffer();
        while (iter.hasNext()) {
            String key = iter.next();
            Object value = map.get(key);
            if (!allrowEmpty && value == null) {// 不允许值为空
                continue;
            }
            if (signStr.length() > 0) {
                signStr.append("&");
            }
            signStr.append(key).append("=").append(value);
        }

        return signStr.toString();
    }


    /**
     * post请求(用于key-value格式的参数)
     *
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, Map params) {


        BufferedReader in = null;

        try {

            // 定义HttpClient

            HttpClient client = new DefaultHttpClient();

            // 实例化HTTP方法

            HttpPost request = new HttpPost();

            request.setURI(new URI(url));


            //设置参数

            List<NameValuePair> nvps = new ArrayList<NameValuePair>();

            for (Iterator iter = params.keySet().iterator(); iter.hasNext(); ) {

                String name = (String) iter.next();

                String value = String.valueOf(params.get(name));

                nvps.add(new BasicNameValuePair(name, value));

            }

            request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));


            HttpResponse response = client.execute(request);

            int code = response.getStatusLine().getStatusCode();

            if (code == 200) {    //请求成功

                in = new BufferedReader(new InputStreamReader(response.getEntity()

                        .getContent(), "utf-8"));

                StringBuffer sb = new StringBuffer("");

                String line = "";

                String NL = System.getProperty("line.separator");

                while ((line = in.readLine()) != null) {

                    sb.append(line + NL);

                }


                in.close();


                return sb.toString();

            } else {   //

                System.out.println("状态码：" + code);

                return null;

            }

        } catch (Exception e) {

            e.printStackTrace();


            return null;

        }

    }



    /**
     * 获取token
     */

    public String getToken(String loginid) {

        String url = "http://127.0.0.1:1217/ssologin/getToken";

        Map<String, String> params = new HashMap<>();

        params.put("appid", "2f60085d-895e-42d5-a87f-f6c2171764b8");

        params.put("loginid", loginid);

        return doPost(url, params);
    }

}
